package com.element.security.single.custom;

import com.element.security.single.model.AuthUserE;
import com.element.security.single.service.IAuthUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.CollectionUtils;

import java.util.Map;

public class CustomAuthProvider implements AuthenticationProvider {

    private final IAuthUserDetailsService authUserDetailsService;

    public CustomAuthProvider(IAuthUserDetailsService authUserDetailsService) {
        this.authUserDetailsService = authUserDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CustomAuthenticationToken authenticationToken = (CustomAuthenticationToken) authentication;
        Map<String, String> params = authenticationToken.getParams();
        if (CollectionUtils.isEmpty(params)) {
            throw new InternalAuthenticationServiceException("params is null");
        }
        AuthUserE authUser = authUserDetailsService.loadUserByParams(params);
        CustomAuthenticationToken authenticationResult = new CustomAuthenticationToken(authUser, authenticationToken, authUser.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CustomAuthenticationToken.class.isAssignableFrom(authentication);
    }
}